import torch
import torch.nn as nn
import time


BN_MOMENTUM = 0.1

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

def upsample(inchannels, outchannels):
    return nn.Sequential(nn.Conv2d(inchannels, outchannels, 1, 1, 0, bias=False),
                         nn.BatchNorm2d(outchannels),
                         nn.Upsample(scale_factor=2, mode='nearest')
                         )
def downsample(inchannels, outchannels):
    return nn.Sequential(nn.Conv2d(inchannels, outchannels, 3, 2, 1, bias=False),
                         nn.BatchNorm2d(outchannels),
                         nn.ReLU(True)
                         )

def transition(inchannels, outchannels, kernel_size, stride, padding):
    return nn.Sequential(nn.Conv2d(inchannels, outchannels, kernel_size, stride, padding, bias=False),
                  nn.BatchNorm2d(outchannels),
                  nn.ReLU(True))
class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
                               bias=False)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion,
                                  momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out
class PSNet(nn.Module):
    def __init__(self):
        super(PSNet, self).__init__()
        self.name = "单凯强"

        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
        self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1,
                               bias=False)
        self.bn2 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
        self.relu = nn.ReLU(inplace=True)

        self.first_layer = self._make_layer(Bottleneck, 64, 64, 4)

        # pos net
        # self.transition_pos_0_0 = transition(256, 32, 3, 1, 1)
        # self.transition_pos_0_1 = transition(256, 64, 3, 2, 1)
        self.transition_pos_0_0 = transition(256, 64, 3, 1, 1)
        self.transition_pos_0_1 = transition(256, 128, 3, 2, 1)

        # self.pos_0_0 = self._make_one_branch(BasicBlock, 4, 32, 32)
        # self.pos_0_1 = self._make_one_branch(BasicBlock, 4, 64, 64)
        # self.cur_pos_downsample_0_0 = downsample(32, 64)
        # self.cur_pos_upsample_0_1 = upsample(64, 32)
        self.pos_0_0 = self._make_one_branch(BasicBlock, 4, 64, 64)
        self.pos_0_1 = self._make_one_branch(BasicBlock, 4, 128, 128)
        self.cur_pos_downsample_0_0 = downsample(64, 128)
        self.cur_pos_upsample_0_1 = upsample(128, 64)

        # self.pos_1_0 = self._make_one_branch(BasicBlock, 4, 32, 32)
        # self.pos_1_1 = self._make_one_branch(BasicBlock, 4, 64, 64)
        # self.cur_pos_downsample_1_0 = downsample(32, 64)
        # self.cur_pos_upsample_1_1 = upsample(64, 32)
        self.pos_1_0 = self._make_one_branch(BasicBlock, 4, 64, 64)
        self.pos_1_1 = self._make_one_branch(BasicBlock, 4, 128, 128)
        self.cur_pos_downsample_1_0 = downsample(64, 128)
        self.cur_pos_upsample_1_1 = upsample(    128, 64)


        # self.pos_f_0 = nn.Sequential(nn.Conv2d(32, 12, kernel_size=3, stride=1, padding=1, bias=False),
        #                                nn.BatchNorm2d(12, momentum=BN_MOMENTUM),
        #                                nn.ReLU())
        # self.pos_f_1 = nn.Sequential(nn.Conv2d(12, 2, kernel_size=3, stride=1, padding=1, bias=False),
        #                                nn.BatchNorm2d(2, momentum=BN_MOMENTUM),
        #                                nn.ReLU())
        self.pos_f_0 = nn.Sequential(nn.Conv2d(64, 32, kernel_size=3, stride=1, padding=1, bias=False),
                                     nn.BatchNorm2d(32, momentum=BN_MOMENTUM),
                                     nn.ReLU())
        self.pos_f_1 = nn.Sequential(nn.Conv2d(32, 2, kernel_size=3, stride=1, padding=1, bias=False),
                                     nn.BatchNorm2d(2, momentum=BN_MOMENTUM),
                                     nn.ReLU())

        #angle net
        # self.transition_angle_0_0 = transition(256, 32, 3, 1, 1)
        # self.transition_angle_0_1 = transition(256, 64, 3, 2, 1)
        self.transition_angle_0_0 = transition(256, 64, 3, 1, 1)
        self.transition_angle_0_1 = transition(256, 128, 3, 2, 1)

        # self.angle_0_0 = self._make_one_branch(BasicBlock, 4, 32, 32)
        # self.angle_0_1 = self._make_one_branch(BasicBlock, 4, 64, 64)
        # self.cur_angle_downsample_0_0 = downsample(32, 64)
        # self.cur_angle_upsample_0_1 = upsample(64, 32)
        self.angle_0_0 = self._make_one_branch(BasicBlock, 4, 64, 64)
        self.angle_0_1 = self._make_one_branch(BasicBlock, 4, 128, 128)
        self.cur_angle_downsample_0_0 = downsample(64, 128)
        self.cur_angle_upsample_0_1 = upsample(128, 64)

        # self.angle_1_0 = self._make_one_branch(BasicBlock, 4, 32, 32)
        # self.angle_1_1 = self._make_one_branch(BasicBlock, 4, 64, 64)
        # self.pos_0_0_2_angle_1_0 = nn.Sequential(nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False),
        #                                          nn.BatchNorm2d(32, momentum=BN_MOMENTUM),
        #                                          nn.ReLU())
        # self.pos_0_1_2_angle_1_1 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
        #                                          nn.BatchNorm2d(64, momentum=BN_MOMENTUM),
        #                                          nn.ReLU())
        # self.cur_angle_downsample_1_0 = downsample(32, 64)
        # self.cur_angle_upsample_1_1 = upsample(64, 32)
        #
        # self.angle_f_0 = nn.Sequential(nn.Conv2d(32, 12, kernel_size=3, stride=2, padding=1, bias=False),
        #                                nn.BatchNorm2d(12, momentum=BN_MOMENTUM),
        #                                nn.Tanh())
        # self.angle_f_1 = nn.Sequential(nn.Conv2d(12, 6, kernel_size=3, stride=2, padding=1, bias=False),
        #                                nn.BatchNorm2d(6, momentum=BN_MOMENTUM),
        #                                nn.Tanh())
        # self.angle_f_2 = nn.Sequential(nn.Conv2d(6, 2, kernel_size=3, stride=2, padding=1, bias=False),
        #                                nn.BatchNorm2d(2, momentum=BN_MOMENTUM),
        #                                nn.Tanh())
        self.angle_1_0 = self._make_one_branch(BasicBlock, 4, 64, 64)
        self.angle_1_1 = self._make_one_branch(BasicBlock, 4, 128, 128)
        self.pos_0_0_2_angle_1_0 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
                                                 nn.BatchNorm2d(64, momentum=BN_MOMENTUM),
                                                 nn.ReLU())
        self.pos_0_1_2_angle_1_1 = nn.Sequential(nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1, bias=False),
                                                 nn.BatchNorm2d(128, momentum=BN_MOMENTUM),
                                                 nn.ReLU())
        self.cur_angle_downsample_1_0 = downsample(64, 128)
        self.cur_angle_upsample_1_1 = upsample(128, 64)

        self.angle_f_0 = nn.Sequential(nn.Conv2d(64, 32, kernel_size=3, stride=2, padding=1, bias=False),
                                       nn.BatchNorm2d(32, momentum=BN_MOMENTUM),
                                       nn.ReLU())
        self.angle_f_1 = nn.Sequential(nn.Conv2d(32, 12, kernel_size=3, stride=2, padding=1, bias=False),
                                       nn.BatchNorm2d(12, momentum=BN_MOMENTUM),
                                       nn.ReLU())
        self.angle_f_2 = nn.Sequential(nn.Conv2d(12, 2, kernel_size=3, stride=2, padding=1, bias=False),
                                       nn.BatchNorm2d(2, momentum=BN_MOMENTUM),
                                       nn.Tanh())
        self.init_weights()


    def _make_layer(self, block,inplanes, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(
                    inplanes, planes * block.expansion,
                    kernel_size=1, stride=stride, bias=False
                ),
                nn.BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
            )

        layers = []
        layers.append(block(inplanes, planes, stride, downsample))
        inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(inplanes, planes))

        return nn.Sequential(*layers)


    def _make_one_branch(self, block, num_blocks, inchannels, outchannels):
        downsample = None
        if inchannels != outchannels:
            downsample = nn.Sequential(
                nn.Conv2d(inchannels, outchannels, kernel_size=1, bias=False),
                nn.BatchNorm2d(outchannels, momentum=BN_MOMENTUM), )

        layers = []
        layers.append(block(inchannels, outchannels,stride=1, downsample=downsample))
        for i in range(1, num_blocks):
            layers.append(block(outchannels, outchannels))
        return nn.Sequential(*layers)
    def forward(self, x):
        start = time.time()
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu(x)
        x = self.first_layer(x)

        y_list = []
        y_list.append(self.transition_pos_0_0(x))
        y_list.append(self.transition_pos_0_1(x))
        y_list.append(self.transition_angle_0_0(x))
        y_list.append(self.transition_angle_0_1(x))

        # y1 = self.transition_pos_0_0(x)
        # y2 = self.transition_pos_0_1(x)
        # y3 = self.transition_angle_0_0(x)
        # y4 = self.transition_angle_0_1(x)

        y_list[0] = self.pos_0_0(y_list[0])
        y_list[1] = self.pos_0_1(y_list[1])
        y_list[2] = self.angle_0_0(y_list[2])
        y_list[3] = self.angle_0_1(y_list[3])

        trans_list= []
        trans_list.append(self.cur_pos_downsample_0_0(y_list[0]))
        trans_list.append(self.cur_pos_upsample_0_1(y_list[1]))
        trans_list.append(self.cur_angle_downsample_0_0(y_list[2]))
        trans_list.append(self.cur_angle_upsample_0_1(y_list[3]))

        x_list = []
        x_list.append(y_list[0] + trans_list[1])
        x_list.append(y_list[1] + trans_list[0])
        x_list.append(y_list[2] + trans_list[3] + self.pos_0_0_2_angle_1_0(y_list[0]))
        x_list.append(y_list[3] + trans_list[2] + self.pos_0_1_2_angle_1_1(y_list[1]))

        y_list[0] = self.pos_1_0(x_list[0])
        y_list[1] = self.pos_1_1(x_list[1])
        y_list[2] = self.angle_1_0(x_list[0])
        y_list[3] = self.angle_1_1(x_list[1])

        trans_list.append(self.cur_pos_downsample_1_0(y_list[0]))
        trans_list.append(self.cur_pos_upsample_1_1(y_list[1]))
        trans_list.append(self.cur_angle_downsample_1_0(y_list[2]))
        trans_list.append(self.cur_angle_upsample_1_1(y_list[3]))

        pos = y_list[0] + trans_list[1]
        angle = y_list[2] + trans_list[3]
        pos = self.pos_f_0(pos)
        pos = self.pos_f_1(pos)
        angle = self.angle_f_0(angle)
        angle = self.angle_f_1(angle)
        angle = self.angle_f_2(angle)
        end = time.time()
        # print(end-start, "///")
        return pos, angle

    def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.normal_(m.weight, std=0.001)
                for name, _ in m.named_parameters():
                    if name in ['bias']:
                        nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.ConvTranspose2d):
                nn.init.normal_(m.weight, std=0.001)
                for name, _ in m.named_parameters():
                    if name in ['bias']:
                        nn.init.constant_(m.bias, 0)